#include "resource.h"

#include "DialogCtrl.hpp"

#include "NetworkListManager.hpp"




namespace GUI
{

	ListViewCtrl* DialogCtrl::lVCtrl = NULL;

	const COLORREF BACK_GROUND_COLOR= 0x000000;

	DialogCtrl::DialogCtrl(HWND hWndParent)
	{
		hDialog = CreateDialog(GetModuleHandle(NULL), MAKEINTRESOURCE (IDD_NSCAN), hWndParent,
			(DLGPROC) &DialogCtrl::DlgProc);

		if (!hDialog)
		{
			wchar_t buf [100];
			wsprintf (buf, L"Error x%x", GetLastError ());
			MessageBox (0, buf, L"CreateDialog", MB_ICONEXCLAMATION | MB_OK);
			return;
		}

		lVCtrl = new ListViewCtrl(hDialog, GetModuleHandle(NULL));
	}

	DialogCtrl::~DialogCtrl()
	{
		DestroyWindow (hDialog);
	}

	WPARAM DialogCtrl::run(int nCmdShow)
	{
		if (IsWindow(hDialog))
		{
			ShowWindow(hDialog, nCmdShow); 
			UpdateWindow(hDialog);
		}
		return 0;
	}

	BOOL CALLBACK DialogCtrl::DlgProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam) 
	{
		HWND hwndOwner; 
		RECT rc, rcDlg, rcOwner; 

		switch (message)
		{
		case WM_INITDIALOG:
			// Get the owner window and dialog box rectangles. 

			if ((hwndOwner = GetParent(hwndDlg)) == NULL) 
			{
				hwndOwner = GetDesktopWindow(); 
			}

			GetWindowRect(hwndOwner, &rcOwner); 
			GetWindowRect(hwndDlg, &rcDlg); 
			CopyRect(&rc, &rcOwner); 

			// Offset the owner and dialog box rectangles so that right and bottom 
			// values represent the width and height, and then offset the owner again 
			// to discard space taken up by the dialog box. 

			OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top); 
			OffsetRect(&rc, -rc.left, -rc.top); 
			OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom); 

			// The new position is the sum of half the remaining space and the owner's 
			// original position. 

			SetWindowPos(hwndDlg, 
				HWND_TOP, 
				rcOwner.left + (rc.right / 2), 
				rcOwner.top + (rc.bottom / 2), 
				0, 0,          // Ignores size arguments. 
				SWP_NOSIZE);



			return TRUE;

		case WM_CTLCOLORDLG:
			{
				HBRUSH g_hbrBackground = CreateSolidBrush(BACK_GROUND_COLOR);
				return (LONG)g_hbrBackground;
			}

		case WM_COMMAND:
			return OnCommand(hwndDlg, message, wParam, lParam);

		case WM_DESTROY:
			PostQuitMessage(0);
			break;

		default: 
			return FALSE; 
		}

		return FALSE;
	}

	BOOL DialogCtrl::OnCommand(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam) 
	{
		int wmId    = LOWORD(wParam);
		int wmEvent = HIWORD(wParam);

		if (LOWORD(wParam) == ID_FIND || LOWORD(wParam) == ID_EXIT)
		{

		}

		switch(wmId)
		{
		case ID_FIND:
			{
				Network::NetworkListManager nLManager;
				Network::NetworkList networkList;
				nLManager.GetNetworks(networkList);
				lVCtrl->Clear();
				UpdateWindow(hwndDlg);
				Sleep(1000);
				lVCtrl->InsertItems(networkList);
			}
			break;
		case ID_EXIT:
			DestroyWindow (hwndDlg);
			break;
		}
		return TRUE;
	}
}